package com.penglecode.netty3.example2;

import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.penglecode.netty3.example1.EchoClientHandler;

public class ClientMessageHandler extends SimpleChannelHandler implements
		ChannelHandler {

	private static final Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);
	
	public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		logger.info(">>> [client].handleUpstream ChannelEvent = " + e);
		super.handleUpstream(ctx, e);
	}

	public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		logger.info(">>> [client].handleDownstream ChannelEvent = " + e);
		super.handleDownstream(ctx, e);
	}

	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		logger.info(">>> [client].messageReceived ChannelEvent = " + e);
		logger.info(">>> [client].messageReceived read message from server in handleUpstream method! message = " + ((MessageEvent)e).getMessage());
		e.getChannel().close();
	}

	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		ObjectMessage message = new ObjectMessage();
		message.setId(System.currentTimeMillis());
		message.setActionName("call service");
		message.setOptTime("2013-07-23 00:09:12");
		message.setOptOper("pengle");
		logger.info(">>> [client].channelConnected ChannelEvent = " + e);
		logger.info(">>> [client].channelConnected writer message to server in handleDownstream method! message = " + message);
		e.getChannel().write(message);
	}

}
